<template>
  <AUploadDragger
    :fileList="[]"
    :multiple="false"
    :accept="getAccept"
    :disabled="getDisabled"
    :beforeUpload="handleUpload"
  >
    <p class="ant-upload-drag-icon">
      <DragOutlined />
    </p>
    <p class="ant-upload-text">{{ t('component.upload.dragUploadText') }}</p>
    <p class="ant-upload-hint" v-if="getDescription">
      {{ getDescription }}
    </p>
  </AUploadDragger>
</template>
<script lang="ts" setup>
  import { computed, ref, watchEffect, watch } from 'vue';
  import { UploadDragger } from 'ant-design-vue';
  import { DragOutlined } from '@ant-design/icons-vue';
  import { useI18n } from '@/hooks/web/useI18n';
  import { useMessage } from '@/hooks/web/useMessage';

  const AUploadDragger = UploadDragger;

  defineOptions({ name: 'UploadDragger' });
  const props = defineProps({
    accept: { type: [String], default: '*' },
    maxSize: { type: Number, default: 100 },
    description: { type: String, default: '' },
    value: { type: String },
    disabled: { type: Boolean, default: false },
  });
  const emit = defineEmits(['update:value', 'change']);

  const { t } = useI18n();
  const { createMessage } = useMessage();

  const getAccept = computed(() => props.accept);
  const getMaxSize = computed(() => props.maxSize);
  const getDescription = computed(() => props.description || '');
  const sourceValue = ref(props.value || '');
  const getDisabled = computed(() => props.disabled || false);

  watchEffect(() => {
    sourceValue.value = props.value || '';
  });

  watch(
    () => sourceValue.value,
    (v: string) => {
      emit('update:value', v);
    },
  );

  /** 处理上传 */
  async function handleUpload(file: File) {
    // const isJpgOrPng =
    //   file.type === 'image/jpeg' ||
    //   file.type === 'image/png' ||
    //   file.type === 'image/bmp' ||
    //   file.type === 'image/gif' ||
    //   file.type === 'image/x-icon';
    // if (!isJpgOrPng) {
    //   createMessage.error(t('component.upload.acceptUpload', [getAccept.value]));
    //   return isJpgOrPng;
    // }
    const fileSizeMB = file.size / 1024 / 1024;
    const isLtMB = fileSizeMB < getMaxSize.value;
    if (!isLtMB) {
      createMessage.error(t('component.upload.maxSize', [getMaxSize.value]));
      return isLtMB;
    }
    const reader = new FileReader();
    reader.readAsDataURL(file);
    sourceValue.value = '';
    reader.onload = function (e) {
      sourceValue.value = (e.target?.result as string) ?? '';
      emit('change', { value: sourceValue.value, fileInfo: file });
      // console.log('handleUpload', { value: sourceValue.value, fileInfo: file });
    };
    return false;
  }
</script>
<style lang="less" scoped></style>
